// 入口函数
$(function () {
  if (!localStorage.getItem("token")) {
    layui.layer.msg("登录失败，token缺失", { icon: 5 }, function () {
      localStorage.removeItem("token");
      // 2. 强制跳转到登录页面
      window.parent.location.href = "/bigevent-end/login.html";
    });
  }
  // 渲染页面
  initArtCateList();
  function initArtCateList() {
    $.ajax({
      url: "/admin/comments",
      method: "get",
      success: function (res) {
        // console.log(res);
        if (res.status !== 0) {
          return layui.layer.msg(res.message, { icon: 5 });
          // return layer.msg(res.message);
        }
        var htmlStr = template("tpl-list", res);
        $("tbody").html(htmlStr);
      },
    });
  }
  // 改变时间样式
  template.defaults.imports.dateFormat = function (dataStr) {
    var dt = new Date(dataStr);
    var y = dt.getFullYear();
    var m = dt.getMonth() + 1;
    m = padZero(m);
    var d = dt.getDate();
    d = padZero(d);

    var hh = dt.getHours();
    hh = padZero(hh);
    var mm = dt.getMinutes();
    mm = padZero(mm);
    var ss = dt.getSeconds();
    ss = padZero(ss);
    return `${y}-${m}-${d}   ${hh}:${mm}:${ss}`;
  };
  function padZero(n) {
    return n < 10 ? "0" + n : n;
  }
  // 删除评论列表
  $("tbody").on("click", ".btn-delete", function () {
    //   console.log(1);
    var id = $(this).attr("data-id");
    layui.layer.confirm("您确定要删除此列表吗？", { icon: 3, title: "提示" }, function (index) {
      $.ajax({
        url: "/admin/comments/" + id,
        method: "DELETE",
        success: function (res) {
          //    console.log(res);
          if (res.status !== 0) {
            return layui.layer.msg(res.message, { icon: 5 });
          }
          layui.layer.msg("删除评论列表成功", { icon: 6 });
          initArtCateList();
        },
      });
    });
  });
});
